<template>
  <div v-if="isOpen" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-10">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-lg p-6 max-h-90vh overflow-y-auto">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-medium">群组信息</h3>
        <button @click="$emit('close')" class="text-gray-400 hover:text-gray-500">
          &times;
        </button>
      </div>

      <div v-if="loading" class="py-10 text-center">
        <div class="text-sm text-gray-500">加载中...</div>
      </div>

      <div v-else-if="error" class="py-10 text-center">
        <div class="text-sm text-red-500">{{ error }}</div>
      </div>

      <div v-else>
        <!-- 群组基本信息 -->
        <div class="mb-6">
          <div class="flex items-center mb-4">
            <div class="h-16 w-16 rounded-full bg-indigo-100 flex items-center justify-center text-4xl">
              {{ processGroupAvatar(groupInfo?.group_avatar) }}
            </div>
            <div class="ml-4">
              <div class="text-xl font-bold">{{ groupInfo?.name }}</div>
              <div class="text-sm text-gray-500">群号: {{ groupInfo?.group_code }}</div>
            </div>
          </div>

          <div class="text-sm text-gray-600 mb-2">
            {{ groupInfo?.description || '暂无群组介绍' }}
          </div>

          <div class="text-xs text-gray-500">
            创建于 {{ formatDate(groupInfo?.created_at) }}
          </div>
        </div>

        <!-- 成员列表 -->
        <div class="mb-6">
          <div class="font-medium text-sm mb-2 flex items-center justify-between">
            <span>成员列表 ({{ groupInfo?.members?.length || 0 }})</span>
            <div v-if="canManageMembers" class="text-xs text-gray-500">
              {{ isCreator ? '群主' : '管理员' }}权限
            </div>
          </div>
          <div class="max-h-60 overflow-y-auto border rounded-md">
            <div v-for="member in groupInfo?.members" :key="member.user_id" class="p-3 border-b last:border-0 flex items-center">
              <div class="h-8 w-8 rounded-full bg-gray-200 flex items-center justify-center text-sm overflow-hidden">
                <img v-if="member.avatar" :src="member.avatar" class="w-full h-full object-cover" />
                <template v-else>{{ member.username?.[0]?.toUpperCase() || '?' }}</template>
              </div>
              <div class="ml-3 flex-1">
                <div class="font-medium text-sm">{{ member.username }}</div>
                <div class="text-xs text-gray-500">
                  <UserRoleBadge :role="getMemberRole(member)" />
                </div>
              </div>
              <!-- 成员管理操作 -->
              <div v-if="canManageMember(member)" class="ml-2 flex items-center space-x-1">
                <!-- 设置/取消管理员 -->
                <button
                  v-if="isCreator && member.user_id !== groupInfo?.creator_id"
                  @click="toggleMemberRole(member)"
                  :disabled="member.processing"
                  class="px-2 py-1 text-xs rounded-md border transition-colors"
                  :class="member.role === 'admin' 
                    ? 'bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100' 
                    : 'bg-gray-50 text-gray-700 border-gray-200 hover:bg-gray-100'"
                >
                  {{ member.processing ? '处理中...' : (member.role === 'admin' ? '取消管理员' : '设为管理员') }}
                </button>
                <!-- 移除成员 -->
                <button
                  v-if="member.user_id !== authStore.user?._id && member.user_id !== groupInfo?.creator_id"
                  @click="removeMember(member)"
                  :disabled="member.processing"
                  class="px-2 py-1 text-xs bg-red-50 text-red-700 border border-red-200 rounded-md hover:bg-red-100 transition-colors"
                >
                  {{ member.processing ? '移除中...' : '移除' }}
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 管理按钮 -->
        <div v-if="canManageGroup && groupInfo?.status !== 'disbanded'" class="pt-4 border-t space-y-2">
          <button @click="$emit('invite')" class="w-full py-2 bg-primary text-white rounded-md hover:bg-blue-600">
            邀请好友
          </button>

          <button @click="$emit('manage-requests')" class="w-full py-2 bg-green-600 text-white rounded-md hover:bg-green-700 relative">
            管理加入申请
            <span v-if="pendingRequestsCount > 0" class="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center">
              {{ pendingRequestsCount > 9 ? '9+' : pendingRequestsCount }}
            </span>
          </button>

          <button @click="leaveGroup" class="w-full py-2 bg-red-500 text-white rounded-md hover:bg-red-600">
            {{ isCreator ? '解散群组' : '退出群组' }}
          </button>
        </div>

        <!-- 普通成员退出按钮 -->
        <div v-else-if="!canManageGroup && groupInfo?.status !== 'disbanded'" class="pt-4 border-t">
          <button @click="leaveGroup" class="w-full py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600">
            退出群组
          </button>
        </div>

        <!-- 群组已解散提示 -->
        <div v-if="groupInfo?.status === 'disbanded'" class="pt-4 border-t">
          <div class="bg-gray-100 rounded-lg p-3 text-center">
            <div class="text-gray-600 text-sm">
              🚨 该群组已于 {{ formatDate(groupInfo?.disbanded_at) }} 解散
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import axios from 'axios';
import { useAuthStore } from '@/stores/auth';
import { useToast } from 'vue-toastification';
import UserRoleBadge from './UserRoleBadge.vue';

const props = defineProps<{
  isOpen: boolean,
  groupId: string
}>();

const emit = defineEmits(['close', 'invite', 'left', 'manage-requests']);

const authStore = useAuthStore();
const toast = useToast();
const loading = ref(false);
const error = ref('');
const groupInfo = ref<any>(null);
const pendingRequestsCount = ref(0);

// 计算当前用户是否是创建者
const isCreator = computed(() => {
  if (!groupInfo.value || !authStore.user) return false;
  return groupInfo.value.creator_id === authStore.user?._id;
});

// 计算当前用户是否是管理员
const isAdmin = computed(() => {
  if (!groupInfo.value || !authStore.user) return false;
  const currentUserMember = groupInfo.value.members?.find((m: any) => m.user_id === authStore.user?._id);
  return currentUserMember?.role === 'admin';
});

// 计算当前用户是否可以管理群组
const canManageGroup = computed(() => {
  return isCreator.value || isAdmin.value;
});

// 计算当前用户是否可以管理成员
const canManageMembers = computed(() => {
  return isCreator.value || isAdmin.value;
});

// 判断是否可以管理某个成员
const canManageMember = (member: any) => {
  if (!canManageMembers.value) return false;
  if (member.user_id === authStore.user?._id) return false; // 不能管理自己
  if (member.user_id === groupInfo.value?.creator_id) return false; // 不能管理群主
  
  // 管理员不能管理其他管理员，只有群主可以
  if (!isCreator.value && member.role === 'admin') return false;
  
  return true;
};

// 获取成员角色
const getMemberRole = (member: any) => {
  if (member.user_id === groupInfo.value?.creator_id) {
    return 'creator';
  }
  return member.role || 'member';
};

// 监听弹窗打开状态，加载数据
watch(() => props.isOpen, (newVal) => {
  if (newVal && props.groupId) {
    loadGroupInfo();
  }
});

// 加载群组信息
async function loadGroupInfo() {
  if (!props.groupId) return;

  loading.value = true;
  error.value = '';

  try {
    const response = await axios.get(`/api/groups/${props.groupId}`);
    groupInfo.value = response.data;
    
    // 为每个成员添加处理状态
    if (groupInfo.value.members) {
      groupInfo.value.members = groupInfo.value.members.map((member: any) => ({
        ...member,
        processing: false
      }));
    }
    
    // 如果当前用户是管理员，加载待处理请求数量
    if (canManageGroup.value) {
      loadPendingRequestsCount();
    }
  } catch (err: any) {
    error.value = err.response?.data?.message || '加载群组信息失败';
  } finally {
    loading.value = false;
  }
}

// 加载待处理请求数量
async function loadPendingRequestsCount() {
  try {
    const response = await axios.get(`/api/groups/${props.groupId}/join-requests`);
    pendingRequestsCount.value = response.data.length;
  } catch (err: any) {
    // 如果没有权限访问，忽略错误
    if (err.response?.status !== 403) {
      console.error('加载待处理请求数量失败:', err);
    }
    pendingRequestsCount.value = 0;
  }
}

// 切换成员角色（设为管理员/取消管理员）
async function toggleMemberRole(member: any) {
  if (!confirm(`确定要${member.role === 'admin' ? '取消' : '设置'} ${member.username} 的管理员权限吗？`)) {
    return;
  }

  member.processing = true;
  try {
    const newRole = member.role === 'admin' ? 'member' : 'admin';
    await axios.put(`/api/groups/${props.groupId}/members/${member.user_id}`, {
      action: 'updateRole',
      role: newRole
    });

    // 更新本地数据
    member.role = newRole;
    toast.success(`已${newRole === 'admin' ? '设置' : '取消'} ${member.username} 的管理员权限`);
  } catch (err: any) {
    toast.error(err.response?.data?.message || '操作失败');
  } finally {
    member.processing = false;
  }
}

// 移除成员
async function removeMember(member: any) {
  if (!confirm(`确定要将 ${member.username} 移出群组吗？`)) {
    return;
  }

  member.processing = true;
  try {
    await axios.put(`/api/groups/${props.groupId}/members/${member.user_id}`, {
      action: 'remove'
    });

    // 从本地列表中移除
    const index = groupInfo.value.members.findIndex((m: any) => m.user_id === member.user_id);
    if (index !== -1) {
      groupInfo.value.members.splice(index, 1);
    }
    
    toast.success(`已将 ${member.username} 移出群组`);
  } catch (err: any) {
    toast.error(err.response?.data?.message || '移除成员失败');
    member.processing = false;
  }
}

// 退出/解散群组
async function leaveGroup() {
  if (!confirm(`确定${isCreator.value ? '解散' : '退出'}该群组吗？`)) {
    return;
  }

  try {
    if (isCreator.value) {
      await axios.delete(`/api/groups/${props.groupId}`);
    } else {
      await axios.post(`/api/groups/${props.groupId}/leave`);
    }

    emit('left');
    emit('close');
  } catch (err: any) {
    error.value = err.response?.data?.message || `${isCreator.value ? '解散' : '退出'}群组失败`;
  }
}

// 格式化日期
function formatDate(dateString: string) {
  return new Date(dateString).toLocaleDateString('zh-CN');
}

// 处理群组头像
function processGroupAvatar(avatar: string) {
  if (!avatar) return '👥'
  
  // 如果包含emoji前缀，去除前缀
  if (avatar.startsWith('emoji:')) {
    return avatar.replace('emoji:', '')
  }
  
  // 如果是图片URL，返回默认emoji（因为这里是纯文本显示）
  if (avatar.startsWith('data:image/') || avatar.startsWith('http')) {
    return '👥'
  }
  
  // 直接返回emoji
  return avatar || '👥'
}

// 初始加载
onMounted(() => {
  if (props.isOpen && props.groupId) {
    loadGroupInfo();
  }
});
</script>

<style scoped>
.max-h-90vh {
  max-height: 90vh;
}
</style>